package userroute

import (
	"power/core/common/errorcode"
	"power/core/dao/userdao"
	"power/core/localwrap"
	"power/core/service/users"
	"power/http/routes"

	"github.com/RocksonZeta/irisx"
	"github.com/kataras/iris/v12"
)

var logUsers = localwrap.GetLogger().Fork("power/http/userroute", "RouteUsers")

//Route /api/user
func RouteUsers(party iris.Party) {
	party.Post("/signin", func(ctx iris.Context) {
		c := ctx.(*irisx.Context)
		var param users.SigninParam
		param.Email = c.CheckBody("email").NotEmpty().String()
		param.Password = c.CheckBody("password").NotEmpty().String()

		logUsers.Debug().Str("path", c.Path()).Interface("signinParam", param).Send()
		r, err := users.UserPrivates{}.Signin(param)
		if err != nil {
			c.JSON(err)
			return
		}
		if r.Uid == 0 {
			c.Err(errorcode.UserNotExists, "No such user.")
			return
		}
		u := users.Users{}.Get(r.Uid)
		c.SetUid(u.Id, localwrap.Config.Session.Ttl)
		c.Ok(r)
	})
	party.Any("/signout", func(ctx iris.Context) {
		c := ctx.(*irisx.Context)
		logUsers.Debug().Str("path", c.Path()).Send()
		c.SetUid(0, 0)
		c.RemoveCookieLocal("sessionid")
		c.Ok(nil)
	})
	party.Get("/", func(ctx iris.Context) {
		c := ctx.(*irisx.Context)
		uid := c.GetUidInt()
		logUsers.Debug().Str("path", c.Path()).Int("uid", uid).Send()
		r := users.Users{}.Get(uid)
		c.Ok(r)
	})
	party.Post("/update", func(ctx iris.Context) {
		c := ctx.(*irisx.Context)
		var param userdao.UsersUpdateParam
		param.Id = c.CheckBody("id").NotBlank().Int(0)
		param.Name = c.CheckBody("name").NotBlank().String()
		logUsers.Debug().Str("path", c.Path()).Interface("param", param).Send()
		routes.Check(c)
		users.Users{}.Update(param)
		c.Ok(nil)
	})
}
